import { createVNode, render } from 'vue';
import MessageComponent from './AlertMessage.vue';

let instance;
const messageQueue = [];

const AlertMessage = (options) => {
    if (typeof options ==='string') {
        options = { message: options };
    }

    const { message, type = 'info', duration = 3000, fill, iconPath } = options;

    const vnode = createVNode(MessageComponent, {
        message,
        type,
        duration,
        fill,
        iconPath,
    });

    const container = document.createElement('div');
    render(vnode, container);
    document.body.appendChild(container);

    instance = vnode.component;

    messageQueue.push(instance);

    // 确保 messageQueue 中有至少两个元素再进行操作
    if (messageQueue.length >= 2) {
        const prevInstance = messageQueue[messageQueue.length - 2];
        const prevEl = prevInstance?.$el;
        const el = instance.$el;
        if (prevEl) {
            el.style.top = `${parseInt(prevEl.style.top) + prevEl.offsetHeight + 10}px`;
        }
    }
};

['success', 'warning', 'error', 'info'].forEach((type) => {
    AlertMessage[type] = (message, duration) => {
        AlertMessage({
            message,
            type,
            duration: duration || 3000,
        });
    };
});

export default AlertMessage;